﻿using AMobiSDK;
using BaoVeThanhDia.Buttons;
using BaoVeThanhDia.FileSetting;
using BaoVeThanhDia.Sound;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input.Touch;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows;
using System.Windows.Navigation;

namespace BaoVeThanhDia
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        UIElementRenderer elementRenderer;
        public static ContentManager contentManager;
        private GameTimer timer;
        private SpriteBatch spriteBatch;
        private List<Button> buttons, settingButtons;
        private Vector2 start, curtouch;
        private string Status;
        private SpriteFont fontSetting;
        public static bool isNen, isHieuUng, isRung;
        FileOption fileoption;
        CustomSoundEffect click;
        private BackgroundWorker bw = new BackgroundWorker();
        private bool isLoaded;
        public MainPage()
        {
            InitializeComponent();
            // Get the content manager from the application
            contentManager = (Application.Current as App).Content;
            // Create a timer for this page
            timer = new GameTimer();
            timer.UpdateInterval = TimeSpan.FromTicks(333333);
            timer.Update += OnUpdate;
            timer.Draw += OnDraw;
            LayoutUpdated += new EventHandler(XNARendering_LayoutUpdated);

            Status = "menu";
            fileoption = new FileOption();
            fileoption.getSetting(ref isNen, ref isHieuUng, ref isRung);

            isLoaded = false;
            AudioManager.Initialize();
            bw.WorkerReportsProgress = true;
            bw.DoWork += new DoWorkEventHandler(bw_DoWork);
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
            bw.RunWorkerAsync();

            buttons = new List<Button>();
            buttons.Add(new Button("", "images/menu/mainbg", Vector2.Zero, Vector2.Zero, new Vector2(600, 360), 4 / 3f));
            buttons.Add(new Button("ten", "images/menu/tengame", new Vector2(325, 50), Vector2.Zero, new Vector2(500, 123), 0.3f));
            buttons.Add(new Button("Play", "images/menu/Choi", new Vector2(295, 350), Vector2.Zero, new Vector2(150, 70), 1.4f));
            buttons.Add(new Button("Exit", "images/menu/thoat", new Vector2(700, 380), Vector2.Zero, new Vector2(80, 84), 1f));
            buttons.Add(new Button("Setting", "images/menu/setting", new Vector2(30, 380), Vector2.Zero, new Vector2(80, 84), 1f));
            buttons.Add(new Button("Face", "images/menu/face", new Vector2(130, 380), Vector2.Zero, new Vector2(80, 84), 1f));
            settingButtons = new List<Button>();
            settingButtons.Add(new Button("", "images/setting/frame", new Vector2(100, 60), Vector2.Zero, new Vector2(100, 60), 6f));
            settingButtons.Add(new Button("", "images/setting/name", new Vector2(250, 70), Vector2.Zero, new Vector2(150, 45), 2f));
            settingButtons.Add(new Button("nen_true", "images/setting/checked", new Vector2(550, 170), Vector2.Zero, new Vector2(50, 50), 1f));
            settingButtons.Add(new Button("nen_false", "images/setting/check", new Vector2(550, 170), Vector2.Zero, new Vector2(50, 50), 1f));
            settingButtons.Add(new Button("effect_true", "images/setting/checked", new Vector2(550, 230), Vector2.Zero, new Vector2(50, 50), 1f));
            settingButtons.Add(new Button("effect_false", "images/setting/check", new Vector2(550, 230), Vector2.Zero, new Vector2(50, 50), 1f));
            settingButtons.Add(new Button("Rung_true", "images/setting/checked", new Vector2(550, 290), Vector2.Zero, new Vector2(50, 50), 1f));
            settingButtons.Add(new Button("Rung_false", "images/setting/check", new Vector2(550, 290), Vector2.Zero, new Vector2(50, 50), 1f));
            settingButtons.Add(new Button("back", "images/setting/trolai", new Vector2(325, 366), Vector2.Zero, new Vector2(150, 66), 1f));
            click = new CustomSoundEffect("sounds/effect/Click_Button");
        }
        void XNARendering_LayoutUpdated(object sender, EventArgs e)
        {
            // make sure page size is valid
            if (ActualWidth == 0 || ActualHeight == 0)
                return;

            // see if we already have the right sized renderer
            if (elementRenderer != null &&
                elementRenderer.Texture != null &&
                elementRenderer.Texture.Width == (int)ActualWidth &&
                elementRenderer.Texture.Height == (int)ActualHeight)
            {
                return;
            }

            // dispose the current renderer
            if (elementRenderer != null)
                elementRenderer.Dispose();

            // create the renderer
            elementRenderer = new UIElementRenderer(this, (int)ActualWidth, (int)ActualHeight);
        }
        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            // Perform a time consuming operation and report progress.
            // System.Threading.Thread.Sleep(50);
            //   worker.ReportProgress()
            AudioManager.LoadSounds("song_menu.ogg");
        }
        private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            isLoaded = true;
            if (MainPage.isNen) AudioManager.PlaySound("song_menu.ogg", true);
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(true);

            // Create a new SpriteBatch, which can be used to draw textures.
            if (MapAndUpgrade.MapAndUpgrade.contentManager != null) MapAndUpgrade.MapAndUpgrade.contentManager.Unload();
            spriteBatch = new SpriteBatch(SharedGraphicsDeviceManager.Current.GraphicsDevice);
            inapp.show("right", 461, 20);
            AdManager.setWidgetCode(
             "fcfc32ae4158ac09082a901da0b3fc59");//chỉ cần gọi hàm setWidgetCode này một lần 
            //duy nhất trong toàn bộ Project
            AdManager advertisement = new AdManager();
            advertisement.OnNavigationTo(this, null, banner300x250, null);

            click.Load(contentManager);
            foreach (Button button in buttons)
            {
                button.Load(contentManager);
            }
            foreach (Button button in settingButtons)
            {
                button.Load(contentManager);
            }
            fontSetting = contentManager.Load<SpriteFont>("fonts/WaveFont");
            if (MainPage.isNen) AudioManager.PlaySound("song_menu.ogg", true);
            // Start the timer
            timer.Start();
            base.OnNavigatedTo(e);
        }
        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            new AdManager().collapseAllUserControls();
            // Stop the timer
            timer.Stop();
            // Set the sharing mode of the graphics device to turn off XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(false);
            AudioManager.StopSound("song_menu.ogg");

            base.OnNavigatedFrom(e);
        }
        private void OnUpdate(object sender, GameTimerEventArgs e)
        {
            if (isLoaded)
            {
                TouchCollection touchs = TouchPanel.GetState();
                foreach (TouchLocation touch in touchs)
                {
                    if (touch.State == TouchLocationState.Pressed)
                    {
                        start = touch.Position;
                        curtouch = touch.Position;
                    }
                    if (touch.State == TouchLocationState.Moved)
                    {
                        #region sự kiện vuốt
                        curtouch = touch.Position;
                        if (Status.Equals("menu"))
                        {
                            foreach (Button button in buttons)
                            {
                                if (!button.getName().Equals("") && !button.getName().Equals("ten"))
                                {
                                    button.isTouch(curtouch);
                                }
                            }
                        }
                        else
                        {
                            foreach (Button button in settingButtons)
                            {
                                if (!button.getName().Equals(""))
                                {
                                    button.isTouch(curtouch);
                                }
                            }
                        }
                        #endregion
                    }
                    if (touch.State == TouchLocationState.Released)
                    {
                        curtouch = touch.Position;
                        if (Status.Equals("menu"))
                        {
                            #region bắt xự kiện trong giao diện menu
                            foreach (Button button in buttons)
                            {
                                if (!button.getName().Equals("") && !button.getName().Equals("ten"))
                                {
                                    if (button.isTouch(curtouch))
                                    {
                                        click.Play();
                                        button.setTouch(false);
                                        if (button.getName().Equals("Exit"))
                                        {
                                            MessageBoxResult result = MessageBox.Show("Bạn có thực sự muốn thoát khỏi chương trình", "", MessageBoxButton.OKCancel);
                                            if (result == MessageBoxResult.OK)
                                            {
                                                Microsoft.Xna.Framework.Game game = new Microsoft.Xna.Framework.Game();
                                                game.Exit();
                                            }
                                        }
                                        else if (button.getName().Equals("Setting"))
                                        {
                                            Status = "setting";
                                        }
                                        else if (button.getName().Equals("Face"))
                                        {
                                            ShareLinkTask shareLinkTask = new ShareLinkTask();

                                            shareLinkTask.Title = "Tớ đang chơi game Bảo vệ thánh địa, có ai chơi cùng mình không ?";
                                            shareLinkTask.LinkUri = new Uri("http://www.windowsphone.com/vi-VN/store/publishers?publisherId=qplay", UriKind.Absolute);
                                            shareLinkTask.Message = "Bảo vệ thánh địa - Game thủ thành - Windows Phone";

                                            shareLinkTask.Show();
                                        }
                                        else if (button.getName().Equals("Play"))
                                        {
                                            NavigationService.Navigate(new Uri("/MapAndUpgrade/MapAndUpgrade.xaml", UriKind.Relative));
                                        }
                                    }
                                }
                            }
                            #endregion
                        }
                        else
                        {
                            #region bắt xự kiện trong giao diện setting
                            foreach (Button button in settingButtons)
                            {
                                if (!button.getName().Equals(""))
                                {
                                    if (button.isTouch(curtouch))
                                    {
                                        click.Play();
                                        button.setTouch(false);
                                        if (button.getName().Equals("nen_true"))
                                        {
                                            isNen = !isNen;
                                            if (isNen)
                                            {
                                                AudioManager.PlaySound("song_menu.ogg", true);
                                            }
                                            else
                                            {
                                                AudioManager.StopSound("song_menu.ogg");
                                            }
                                        }
                                        else if (button.getName().Equals("effect_true"))
                                        {
                                            isHieuUng = !isHieuUng;
                                        }
                                        else if (button.getName().Equals("Rung_true"))
                                        {
                                            isRung = !isRung;
                                        }
                                        else if (button.getName().Equals("back"))
                                        {
                                            fileoption.SaveFile(isNen, isHieuUng, isRung);
                                            Status = "menu";
                                        }
                                    }
                                }
                            }
                            #endregion
                        }
                    }
                }
            }
        }
        private void OnDraw(object sender, GameTimerEventArgs e)
        {
            SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(Color.Black);
            elementRenderer.Render();
            // TODO: Add your drawing code here 
            spriteBatch.Begin();
            if (isLoaded)
            {
                foreach (Button button in buttons)
                {
                    if (button.getName().Equals("ten")) button.ZoomDraw(spriteBatch, 0.3f, 1f);
                    else
                        button.Draw(spriteBatch, Vector2.Zero);
                }
                if (Status.Equals("setting"))
                {
                    foreach (Button button in settingButtons)
                    {
                        if (isNen && button.getName().Equals("nen_false")) { }
                        else if (!isNen && button.getName().Equals("nen_true")) { }
                        else if (isHieuUng && button.getName().Equals("effect_false")) { }
                        else if (!isHieuUng && button.getName().Equals("effect_true")) { }
                        else if (isRung && button.getName().Equals("Rung_false")) { }
                        else if (!isRung && button.getName().Equals("Rung_true")) { }
                        else
                            button.Draw(spriteBatch, Vector2.Zero);
                        spriteBatch.DrawString(fontSetting, "Âm thanh nền", new Vector2(200, 180), Color.White);
                        spriteBatch.DrawString(fontSetting, "Âm thanh hiệu ứng", new Vector2(200, 240), Color.White);
                        spriteBatch.DrawString(fontSetting, "Chế độ rung", new Vector2(200, 300), Color.White);
                    }
                }
                spriteBatch.Draw(elementRenderer.Texture, Vector2.Zero, Color.White);
            }
            else
            {
                foreach (Button button in buttons)
                {
                    if (button.getName().Equals("")) button.Draw(spriteBatch, Vector2.Zero);
                    spriteBatch.DrawString(fontSetting, "Loading . . .", new Vector2(630, 450), Color.White);
                }
            }
            spriteBatch.End();
        }
        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            click.Play();
            if (Status.Equals("menu"))
            {
                MessageBoxResult result = MessageBox.Show("Bạn có thực sự muốn thoát khỏi chương trình", "", MessageBoxButton.OKCancel);
                if (result == MessageBoxResult.OK)
                {
                    Microsoft.Xna.Framework.Game game = new Microsoft.Xna.Framework.Game();
                    game.Exit();
                }
                else e.Cancel = true;
            }
            else
            {
                fileoption.SaveFile(isNen, isHieuUng, isRung);
                Status = "menu";
                e.Cancel = true;
            }
        }
    }
}